import axios from 'axios'
import type {
    AxiosError,
    AxiosInstance,
    InternalAxiosRequestConfig,
    AxiosResponse,
} from 'axios'
import { useStore } from '@/stores'
import { Message } from '@arco-design/web-vue'

//接口地址
const baseURL = import.meta.env.VITE_SERVER_URL

//创建axios实例
const service: AxiosInstance = axios.create({
    baseURL,
    //超时时间
    timeout: 15000,
})

//添加请求拦截器
service.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        const store = useStore()
        //在发送请求之前做些什么
        const token = store.userInfo.token
        if (token) {
            config.headers.Authorization = token
        }
        return config
    },
    (error: AxiosError) => {
        //对请求错误做些什么
        console.log(error, '请求错误:request-error')

        return Promise.reject(error)
    },
)

//添加响应拦截器
service.interceptors.response.use(
    (response: AxiosResponse) => {
        //对响应数据做点什么
        return response.data
    },
    (error: AxiosError) => {
        //对响应错误做点什么
        console.log(error, '响应错误:response-error')

        if (error && error.response) {
            switch (error.response.status) {
                case 400:
                    error.message = '请求错误'
                    break
                case 401:
                    error.message = '未授权，请登录'
                    break
                case 403:
                    error.message = '拒绝访问'
                    break
                case 404:
                    error.message = `请求地址出错: ${error.response.config.url}`
                    break
                case 408:
                    error.message = '请求超时'
                    break
                case 500:
                    error.message = '服务器内部错误'
                    break
                case 501:
                    error.message = '服务未实现'
                    break
                case 502:
                    error.message = '网关错误'
                    break
                case 503:
                    error.message = '服务不可用'
                    break
                case 504:
                    error.message = '网关超时'
                    break
            }

            const errorInfo = {
                code: error.response.status,
                message: error.message,
            }

            console.log('errorInfo:', errorInfo)
            Message.error(`${errorInfo.code}--${errorInfo.message}`)
        } else {
            const errorInfo = {
                message: error.message,
            }
            console.log('errorInfo:', errorInfo)
            Message.error(errorInfo.message)
        }

        //可以对错误信息进行集中操作，统一管理
        return Promise.reject(error)
    },
)

export default service
